<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body>
<button onclick="notifyMe()">通知我!</button>
</body>
<script type="text/javascript">
    let isSubscribed = false;
    let swRegistration = null;
    const applicationServerPublicKey = 'BBs-FGCruOsExeG7fp4GshgcgIk_3mHYW8buw833Ij-te0eWSb_z7MBWSm0zWzVPMMEQv2fK0VA93K1TPqsz7as';


    function urlB64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding)
            .replace(/\-/g, '+')
            .replace(/_/g, '/');

        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);

        for (let i = 0; i < rawData.length; ++i) {
            outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
    }

    // 初始化状态
    function initializeUI() {
        // Set the initial subscription value
        swRegistration.pushManager.getSubscription()
            .then(function (subscription) {
                isSubscribed = !(subscription === null);
                if (isSubscribed) {
                    console.log('用户拒绝.');
                    subscribeUser();
                } else {
                    console.log('用户允许.');
                    subscribeUser();

                }
                updateBtn();
            });
    }

    function updateBtn() {
        if (Notification.permission === 'denied') {
            updateSubscriptionOnServer(null);
            return;
        }
    }

    // function updateSubscriptionOnServer(subscription) {
    //     // TODO: 将订阅发送到应用程序服务器
    //     if (subscription) {
    //         console.log("wwwwwwwwwwwwwwwwwwwww", JSON.stringify(subscription));
    //     } else {
    //         console.log("wwwwwwwwwwwwwwwwwwwww");
    //     }
    // }

    function updateSubscriptionOnServer(subscription) {
        console.log("5")
        // Get public key and user auth from the subscription object
        var key = subscription.getKey ? subscription.getKey('p256dh') : '';
        var auth = subscription.getKey ? subscription.getKey('auth') : '';


        console.log("wwwwwwwwwwwwwwwwwwwww:",JSON.stringify({
            endpoint: subscription.endpoint,
            // Take byte[] and turn it into a base64 encoded string suitable for
            // POSTing to a server over HTTP
            key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
            auth: auth ? btoa(String.fromCharCode.apply(null, new Uint8Array(auth))) : ''
        }));

        // This example uses the new fetch API. This is not supported in all
        // browsers yet.
        return fetch('/profile/subscription', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                endpoint: subscription.endpoint,
                // Take byte[] and turn it into a base64 encoded string suitable for
                // POSTing to a server over HTTP
                key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
                auth: auth ? btoa(String.fromCharCode.apply(null, new Uint8Array(auth))) : ''
            })
        });
    }

    function subscribeUser() {
        // 转换公钥
        const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);

        swRegistration.pushManager.subscribe({
            // 该参数保证您每次发送推送消息时都会显示通知
            userVisibleOnly: true,
            applicationServerKey: applicationServerKey
        })
            .then(function (subscription) {
                // 已订阅
                console.log('用户订阅.');
                updateSubscriptionOnServer(subscription);
                isSubscribed = true;
                updateBtn();
            })
            .catch(function (error) {
                console.log('用户未订阅: ', error);
                updateBtn();
            });
    }

    // 开始通知
    function notifyMe() {
        // 检查浏览器是否支持
        if ('serviceWorker' in navigator && 'PushManager' in window) {
            console.log('SWorker and Push 都支持');

            navigator.serviceWorker.register('./assets/work/notification.js')
                .then(function (swReg) {
                    console.log('sw注册成功', swReg);

                    swRegistration = swReg;
                    initializeUI();
                })
                .catch(function (error) {
                    console.error('SW Error', error);
                });
        } else {
            console.warn('Push messaging 不支持');
        }

    }

    // function notifyMe() {
    //     console.log("1")
    //     if ('serviceWorker' in navigator) {
    //         console.log("2")
    //         navigator.serviceWorker.register('./assets/work/notification.js').then(initialiseState);
    //     } else {
    //         console.warn('Service workers are not supported in this browser.');
    //     }
    //
    // }
    // function initialiseState() {
    //     console.log("3")
    //     // Check if desktop notifications are supported
    //     if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
    //         console.log('Notifications aren\'t supported.');
    //         return;
    //     }
    //
    //     // Check if user has disabled notifications
    //     // If a user has manually disabled notifications in his/her browser for
    //     // your page previously, they will need to MANUALLY go in and turn the
    //     // permission back on. In this statement you could show some UI element
    //     // telling the user how to do so.
    //     if (Notification.permission === 'denied') {
    //         console.log('The user has blocked notifications.');
    //         return;
    //     }
    //
    //     // Check is push API is supported
    //     if (!('PushManager' in window)) {
    //         console.log('Push messaging isn\'t supported.');
    //         return;
    //     }
    //
    //     navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
    //         console.log("6")
    //         // Get the push notification subscription object
    //         serviceWorkerRegistration.pushManager.getSubscription().then(function (subscription) {
    //             console.log("7")
    //             // If this is the user's first visit we need to set up
    //             // a subscription to push notifications
    //             if (!subscription) {
    //                 subscribe();
    //                 console.log("8")
    //                 return;
    //             }
    //
    //             // Update the server state with the new subscription
    //             sendSubscriptionToServer(subscription);
    //         })
    //             .catch(function(err) {
    //                 // Handle the error - show a notification in the GUI
    //                 console.log('Error during getSubscription()', err);
    //             });
    //     });
    // }
    //
    // /**
    //  * Step three: Create a subscription. Contact the third party push server (for
    //  * example mozilla's push server) and generate a unique subscription for the
    //  * current browser.
    //  */
    // function subscribe() {
    //     console.log("4")
    //     navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
    //
    //         // Contact the third party push server. Which one is contacted by
    //         // pushManager is  configured internally in the browser, so we don't
    //         // need to worry about browser differences here.
    //         //
    //         // When .subscribe() is invoked, a notification will be shown in the
    //         // user's browser, asking the user to accept push notifications from
    //         // <yoursite.com>. This is why it is async and requires a catch.
    //         serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true}).then(function (subscription) {
    //
    //             // Update the server state with the new subscription
    //             return sendSubscriptionToServer(subscription);
    //         })
    //             .catch(function (e) {
    //                 if (Notification.permission === 'denied') {
    //                     console.warn('Permission for Notifications was denied');
    //                 } else {
    //                     console.error('Unable to subscribe to push.', e);
    //                 }
    //             });
    //     });
    // }
    //
    // /**
    //  * Step four: Send the generated subscription object to our server.
    //  */
    // function sendSubscriptionToServer(subscription) {
    //     console.log("5")
    //     // Get public key and user auth from the subscription object
    //     var key = subscription.getKey ? subscription.getKey('p256dh') : '';
    //     var auth = subscription.getKey ? subscription.getKey('auth') : '';
    //
    //
    //     console.log("wwwwwwwwwwwwwwwwwwwww:",JSON.stringify({
    //         endpoint: subscription.endpoint,
    //         // Take byte[] and turn it into a base64 encoded string suitable for
    //         // POSTing to a server over HTTP
    //         key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
    //         auth: auth ? btoa(String.fromCharCode.apply(null, new Uint8Array(auth))) : ''
    //     }));
    //
    //     // This example uses the new fetch API. This is not supported in all
    //     // browsers yet.
    //     return fetch('/profile/subscription', {
    //         method: 'POST',
    //         headers: {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify({
    //             endpoint: subscription.endpoint,
    //             // Take byte[] and turn it into a base64 encoded string suitable for
    //             // POSTing to a server over HTTP
    //             key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
    //             auth: auth ? btoa(String.fromCharCode.apply(null, new Uint8Array(auth))) : ''
    //         })
    //     });
    // }




</script>
</html>
